//
//  LotteryWheelView.m
//  MSDemo
//
//  Created by ms on 2024/10/30.
//

#import "LotteryWheelView.h"

@interface LotteryWheelView ()<CAAnimationDelegate>

@property (nonatomic, assign) NSInteger targetSection;
@property (nonatomic, copy) void (^complete)(void);

@end

@implementation LotteryWheelView

/** 动画开始 */
- (void)ms_startAnimaition:(NSInteger)targetSection complete:(void (^)(void))complete
{
    self.complete = complete;
    self.targetSection = targetSection;
    // 播放转动音效
    [self ms_playSoundWithFilename:@"lotteryWheel" fileExtension:@"MP3"];
    /// 相邻两个分割点间的弧度
    CGFloat angleStep = 2 * M_PI / self.numberOfDivisions;
    //控制圈数
    NSInteger turnsNum = arc4random()%5+1;
    turnsNum = 8;
    
    CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    // 顺时针旋转，先转N圈，再转到对应角度（这里需要用360减去对应角度，逆时针旋转不用减直接用即可）
    rotationAnimation.toValue = [NSNumber numberWithFloat:2 * M_PI * turnsNum + (2 * M_PI - targetSection * angleStep)];
    rotationAnimation.duration = 3.0f;
    rotationAnimation.cumulative = YES;
    rotationAnimation.delegate = self;
    //由快变慢
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    rotationAnimation.fillMode=kCAFillModeForwards;
    rotationAnimation.removedOnCompletion = NO;
    
    [self.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}
/** 动画开始 */
- (void)ms_startAnimaition
{
    // 播放转动音效
//    [self ms_playSoundWithFilename:@"lotteryWheel" fileExtension:@"MP3"];
    
    CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    // 顺时针旋转，先转N圈
    rotationAnimation.toValue = [NSNumber numberWithFloat:2 * M_PI * 3];
    rotationAnimation.speed = 1;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = MAXFLOAT;
    // 保持动画结束后的状态不变
    rotationAnimation.fillMode=kCAFillModeForwards;
    rotationAnimation.removedOnCompletion = NO;
    
    [self.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}


#pragma mark - CAAnimationDelegate
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    /// 相邻两个分割点间的弧度
    CGFloat angleStep = 2 * M_PI / self.numberOfDivisions;
    CGFloat targetAngle = 2 * M_PI - self.targetSection * angleStep;
    // 创建一个快速旋转到目标位置的动画，这里使用CATransaction来禁用隐式动画
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    self.transform = CGAffineTransformMakeRotation(targetAngle);
    [CATransaction commit];
    
    
    
    // 震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    // 回调
    if (self.complete) self.complete();
}


#pragma mark - UI
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = UIColor.clearColor;
    }
    
    return self;
}
- (void)layoutSubviews
{
    [super layoutSubviews];

    if (self.numberOfDivisions <= 1 || !self.items || self.items.count != self.numberOfDivisions) return; // 无效输入，不布局

    /// 圆心
    CGPoint center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
    /// 半径
    CGFloat radius = MIN(self.bounds.size.width, self.bounds.size.height) / 2;
    /// 相邻两个分割点间的弧度
    CGFloat angleStep = 2 * M_PI / self.numberOfDivisions;
    CGFloat size = MIN(100 * MS_ADAPTATION_RATIO * 6 / self.numberOfDivisions, 100 * MS_ADAPTATION_RATIO);
    
    // 移除所有子视图
    for (UIView *subview in self.subviews)
    {
        [subview removeFromSuperview];
    }
    
    for (NSInteger i = 0; i < self.numberOfDivisions; i++)
    {
        /// 开始分割点弧度，逆时针方向偏移 90 度后再偏移半个弧度，使第一个区域处于正上方
        CGFloat startAngle = i * angleStep - (M_PI_2 + angleStep / 2);
        /// 结束分割点弧度，逆时针方向偏移 90 度后再偏移半个弧度，使第一个区域处于正上方
        CGFloat endAngle = (i + 1) * angleStep - (M_PI_2 + angleStep / 2);
        /// 中间分割点弧度
        CGFloat midAngle = (startAngle + endAngle) / 2;
        // 奖品标签的位置
        CGPoint labelPoint = CGPointMake(center.x + cos(midAngle) * radius * 0.8, center.y + sin(midAngle) * radius * 0.8);
        // 奖品图片的位置
        CGPoint imagePoint = imagePoint = CGPointMake(center.x + cos(midAngle) * radius * 0.55, center.y + sin(midAngle) * radius * 0.55);
        /// 为了将标签和图片放置在正确的方向上，我们需要计算旋转角度。加上 90 度，因为 UI 元素的默认方向是向上
        CGFloat rotation = midAngle + M_PI_2;
        
        // 创建奖品名称标签
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300 * MS_ADAPTATION_RATIO * 6 / self.numberOfDivisions, 62 * MS_ADAPTATION_RATIO)]; // 宽度和高度可以根据需要调整
        label.text = self.items[i][@"title"];
        label.textAlignment = NSTextAlignmentCenter;
        label.center = labelPoint;
        label.transform = CGAffineTransformMakeRotation(rotation); // 旋转标签以匹配转盘的方向
        [self addSubview:label];
        
        // 创建奖品图片视图
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size, size)]; // 宽度和高度可以根据需要调整
        NSString *image = self.items[i][@"image"];
        
        if ([image containsString:@"http"])
        {
            [imageView ms_setImageWithURLString:image];
        }
        else
        {
            imageView.image = [UIImage imageNamed:image];
        }
        
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.center = imagePoint;
        imageView.transform = CGAffineTransformMakeRotation(rotation); // 旋转图片视图以匹配转盘的方向
        [self addSubview:imageView];
    }
    
    // 触发重绘以绘制等分线
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    
    if (self.numberOfDivisions <= 1) return; // 无需绘制等分线
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    /// 圆心
    CGPoint center = CGPointMake(rect.size.width / 2, rect.size.height / 2);
    /// 半径
    CGFloat radius = MIN(rect.size.width, rect.size.height) / 2;
    // 相邻两个分割点间的弧度
    CGFloat angleStep = 2 * M_PI / self.numberOfDivisions;
    // 绘制背景
    for (NSInteger i = 0; i < self.numberOfDivisions; i++)
    {
        // 开始角度
        CGFloat startAngle = i * angleStep - (M_PI_2 + angleStep / 2);
        // 结束角度
        CGFloat endAngle = (i + 1) * angleStep - (M_PI_2 + angleStep / 2);

        // 绘制背景色(bgColors)
        UIColor *fillColor = self.bgColors[i % self.bgColors.count];
        CGContextBeginPath(context);
        CGContextMoveToPoint(context, center.x, center.y);
        CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, 0);
        CGContextClosePath(context);
        CGContextSetFillColorWithColor(context, fillColor.CGColor);
        CGContextFillPath(context);
    }
    // 绘制等分线
    for (NSInteger i = 0; i < self.numberOfDivisions; i++)
    {
        // 开始角度
        CGFloat startAngle = i * angleStep - (M_PI_2 + angleStep / 2);
        // 绘制等分线(divisionsLineColor)
        CGContextBeginPath(context);
        CGContextMoveToPoint(context, center.x, center.y);
        CGContextAddLineToPoint(context, center.x + cos(startAngle) * radius, center.y + sin(startAngle) * radius);
        CGContextSetLineWidth(context, 8 * MS_ADAPTATION_RATIO);
        CGContextSetStrokeColorWithColor(context, self.divisionsLineColor.CGColor);
        
        CGContextStrokePath(context);
    }
    
    // 如果需要绘制一个外圈，可以取消注释以下代码
    /*
    CGContextBeginPath(context);
    CGContextAddArc(context, center.x, center.y, radius, 0, 2 * M_PI, 0);
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextStrokePath(context);
    */
}


#pragma mark - getter
- (UIColor *)divisionsLineColor
{
    if (!_divisionsLineColor)
    {
        _divisionsLineColor = MS_HEX_COLOR(0xF3AC44);
    }
    
    return _divisionsLineColor;
}
- (NSArray<UIColor *> *)bgColors
{
    if (!_bgColors)
    {
        _bgColors = @[MS_HEX_COLOR(0xFEE08C), MS_HEX_COLOR(0xFEF2CD)];
    }
    
    return _bgColors;
}


#pragma mark - setter
- (void)setNumberOfDivisions:(NSInteger)numberOfDivisions
{
    _numberOfDivisions = numberOfDivisions;
    [self setNeedsLayout]; // 触发重新布局和重绘
}
- (void)setItems:(NSArray<NSDictionary *> *)items
{
    _items = items;
    [self setNeedsLayout]; // 触发重新布局
}

@end
